package com.example.nio.bio;

import java.io.IOException;
import java.io.InputStream;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;
import java.util.concurrent.TimeUnit;

/**
 * @auther:lgb
 * @Date: 2021/5/3
 */
public class BIOTcpServer {
    public static void main(String[] args) {
        ServerSocket serverSocket = null;
        int recvMsgSize = 0;
        InputStream in = null;
        try {
            //开一个监听2333端口的TCP服务
            serverSocket = new ServerSocket(2333);
            byte[] recvBuf = new byte[1024];
            while (true) {
                //探听有没有新的客户端连接进来，没有就阻塞
                Socket clntSocket = serverSocket.accept();
                //通过跟服务连接上的客户端socket，拿到客户端地址
                SocketAddress clientAddress = clntSocket.getRemoteSocketAddress();
                System.out.println("连接成功，处理客户端：" + clientAddress);
                // 延迟10ms 来模拟粘包现象
                Thread.sleep(10);
                //数据流
                in = clntSocket.getInputStream();
                //读取发送的数据，当客户端未断开连接，且不往服务端发数据的时候，说明一直处于准备读的状态，会一直阻塞下去，直到有数据写入（读就绪）
                while ((recvMsgSize = in.read(recvBuf)) != -1) {
                    byte[] temp = new byte[recvMsgSize];
                    System.arraycopy(recvBuf, 0, temp, 0, recvMsgSize);
                    System.out.println("收到客户端" + clientAddress + "的消息内容：" + new String(temp)); //打印消息
                }
                System.out.println("-----------------------------------");
            }
        } catch (IOException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            try {
                if (serverSocket != null) {
                    System.out.println("socket关闭！");
                    serverSocket.close();
                }
                if (in != null) {
                    System.out.println("stream连接关闭！");
                    in.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
